<?php
namespace app\admin\controller;
use app\admin\common\Base;
use think\Db;
use think\facade\Request;
use think\Exception;
use app\admin\model\AdminUser as AdminUserModel;

/**
* 管理员控制器
*/
class AdminUser extends Base{

    use \app\admin\traits\BaseFn;

    protected $model = null;

    public function initialize(){
        parent::initialize();
        $this->model = new AdminUserModel();
    }

    /**
     * 列表
     */
    public function index(){
        if(Request::isAjax()){

            list($where,$sort) = $this->buildQuery();

            $list = $this->model
                ->where($where)
                ->order('id desc')
                ->paginate(Request::param('pageSize'))
                ->each(function ($item,$key){
                    //角色
                    $roles = Db::name('privilege_role')->where([['id','in',$item['role_ids']]])->column('role_name');
                    $item['role_names'] = '';
                    if($roles)
                        $item['role_names'] = implode(',',$roles);
                    //组长
                    if($item['leader']==0){
                        $item['leader'] = '';
                    }else{
                        $item['leader'] = Db::name('admin_user')->where(['id'=>$item['leader'],])->value('nickname');
                    }
                    return $item;
                });

            $list = $list->toArray();
            $data = [
                "total"=>$list['total'],
                'rows'=>$list['data'],
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * 添加
     */
    public function add(){
        if(Request::isAjax()){
            $code = 0;
            $msg = 'success';
            $data = null;
            try{
                $post = Request::param();
                //判断用户名是否存在
                $where = [];
                $where[] = ['username','eq',$post['username']];
                $count = $this->model->where($where)->count();
                if($count>0){
                    $code = 10002;
                    throw new Exception('用户名已存在');
                }

                if( trim($post['extennum']) ){
                    if( !is_numeric($post['extennum']) )
                        throw new Exception('分机号必须是数字字符');

                    $where = [];
                    $where[] = ['extennum','eq',$post['extennum']];
                    $count = $this->model->where($where)->count();
                    if($count>0){
                        $code = 10003;
                        throw new Exception('用户分机号已存在');
                    }
                }

                foreach ($post as $key=>$value){
                    if(substr($key,-4) === 'time'){
                        //时间自动转为时间戳
                        $post[$key] = strtotime($value);
                    }
                }
                $post['add_time'] = time();
                $post['password'] = md5($post['password']);
                if(isset($post['role_ids'])){
                    if( empty($post['role_ids']) )
                        throw new Exception('请选择角色');

                    //判断 【客服用户】 是否关联了【组长】
                    if( in_array(4/*客服角色*/, $post['role_ids']) ){
                        if(empty($post['leader']))
                            throw new Exception('请为客服用户关联组长');
                    }

                    $post['role_ids'] = implode(',',$post['role_ids']);
                    if( '' == $post['role_ids'] )
                        throw new Exception('请选择角色');
                }
                $insert = $this->model->allowField(true)->save($post);//过滤数据库字段写入

                if($insert){
                    $msg = "添加成功";
                }else{
                    $code = 10001;
                    throw new Exception('添加失败');
                }

            }catch (Exception $e){
                $code = 10001;
                $msg = $e->getMessage();
            }

            return json(['data'=>$data,'msg'=>$msg,'code'=>$code]);
        }

        //获取所有角色输出
        $roles = Db::name('privilege_role')->select();
        $this->assign('roles', $roles);

        //获取【组长角色（id=3）】用户列表
        $leaders = AdminUserModel::whereOr([
            ['role_ids', 'eq', '3'],
            ['role_ids', 'like', '3,%'],
            ['role_ids', 'like', '%,3'],
        ])->field('id,username,nickname,extennum')->select();
        $this->assign('leaders', $leaders);

        return $this->fetch();
    }

    /**
     * 编辑
     */
    public function edit(){
        if(Request::isAjax()){
            $code = 0;
            $msg = 'success';
            $data = null;
            try{
                $where = [
                    'id'=>Request::param('id'),
                ];
                $update = Request::except('id');

                //判断用户名是否存在
                $map = [];
                $map[] = ['username','eq',$update['username']];
                $map[] = ['id','neq',$where['id']];
                $count = $this->model->where($map)->count();
                if($count>0){
                    $code = 10002;
                    throw new Exception('用户名已存在');
                }

                //分机检测
                $extennum = Request::param('extennum','','trim');
                if( !is_numeric($extennum) )
                    throw new Exception('分机号必须是数字字符');
                if( $extennum ){
                    $map2 = [];
                    $map2[] = ['extennum','eq',$extennum];
                    $map2[] = ['id','neq',$where['id']];
                    $count = $this->model->where($map2)->count();
                    if($count>0){
                        $code = 10003;
                        throw new Exception('用户分机号已存在');
                    }
                }

                foreach ($update as $key=>$value){
                    if(substr($key,-4) === 'time'){
                        //时间自动转为时间戳
                        $update[$key] = strtotime($value);
                    }
                }
                if($update['password']!=''){
                    $update['password'] = md5($update['password']);
                }else{
                    unset($update['password']);
                }

                if(isset($update['role_ids'])){
                    if( empty($update['role_ids']) )
                        throw new Exception('请选择角色');

                    //判断 【客服用户】 是否关联了【组长】
                    if( in_array(4/*客服角色*/, $update['role_ids']) ){
                        if(empty($update['leader']))
                            throw new Exception('请为客服用户关联组长');
                    }

                    $update['role_ids'] = implode(',',$update['role_ids']);
                    if( '' == $update['role_ids'] )
                        throw new Exception('请选择角色');

                }else{
                    $update['role_ids'] = '';
                }
                //admin(id=1) 超级管理员的角色必须 固定 为1
                if( $where['id'] == 1 ){
                    $update['role_ids'] = '1';
                }

                $this->model->save($update,$where);
                $msg = "保存成功";

            }catch (Exception $e){
                $code = 10001;
                $msg = $e->getMessage();
            }

            return json(['data'=>$data,'msg'=>$msg,'code'=>$code]);
        }
        $where = Request::param();
        $data = $this->model->where($where)->find();
        $data['role_ids'] = explode(',',$data['role_ids']);
        $this->assign('data',$data);
        //获取所有角色输出
        $roles = Db::name('privilege_role')->select();
        $this->assign('roles',$roles);

        //获取【组长角色（id=3）】用户列表
        $leaders = AdminUserModel::whereOr([
            ['role_ids', 'eq', '3'],
            ['role_ids', 'like', '3,%'],
            ['role_ids', 'like', '%,3'],
        ])->field('id,username,nickname,extennum')->select();
        $this->assign('leaders', $leaders);

        return $this->fetch();
    }

    /**
     * 编辑
     */
    public function editProfile(){
        $id = session('admin.id');
        if(Request::isAjax()){
            $code = 0;
            $msg = 'success';
            $data = null;
            try{
                $where = [
                    'id'=>$id,
                ];
                $update = Request::except('id');

                foreach ($update as $key=>$value){
                    if(substr($key,-4) === 'time'){
                        //时间自动转为时间戳
                        $update[$key] = strtotime($value);
                    }
                }
                if($update['password']!=''){
                    $update['password'] = md5($update['password']);
                }else{
                    unset($update['password']);
                }

                $this->model->save($update,$where);
                $msg = "保存成功";
                $data = $update;

                unset($update['password']);
                session('admin', array_merge(session('admin'), $update));   //防止刷新后丢失logo

            }catch (Exception $e){
                $code = 10001;
                $msg = $e->getMessage();
            }

            return json(['data'=>$data,'msg'=>$msg,'code'=>$code]);
        }

        $where = ['id'=>$id,];
        $data = $this->model->where($where)->find();
        $this->assign('data',$data);

        return $this->fetch();
    }

    //删除
    public function del(){
        $ids = Request::param('ids/a');
        if( in_array(1, $ids) ){
            $code = 1;
            $msg = '不能删除超级管理员';
            $data = null;
            return json(['data'=>$data,'msg'=>$msg,'code'=>$code]);
        }

        //调用trait基类
        return $this->delete();
    }

}
